﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Jint;
using System.Net;
using Jint.Native;
using System.IO;

namespace jsweb
{
   class Form
   {
      public Form(HttpListenerContext context, JintEngine jsEngine)
      {
         // If form data exists, fill the form object
         if (context.Request.HasEntityBody)
         {
            // Read body
            var stream = new StreamReader(context.Request.InputStream);
            var body = stream.ReadToEnd();

            // Create js object
            JsObject formObj = new JsObject();
            
            // Split and fill js object
            foreach (var parameter in body.Split('&'))
            {
               // Split
               var keyValue = parameter.Split('=');
               var value = keyValue[1].Replace('+', ' ');
               formObj[keyValue[0]] = new JsString(System.Web.HttpUtility.UrlDecode(value, context.Request.ContentEncoding), null);
            }

            // Set js parameter
            jsEngine.SetParameter("Form", formObj);
         }
      }
   }
}
